#include <stdio.h> 
#include <string.h>

#include "cdefs.h"
#include "cbig_num.h"
#include "crsa.h"


static cbig_num_t modexp(cbig_num_t a, cbig_num_t b, cbig_num_t n) {
    cbig_num_t               y, zero;
   	
	bzero(&zero, sizeof(zero));
	y = cbig_num_parse("1", 16);
	
    while(cbig_num_cmp(b, zero) != 0) {
        if(b.d[CBIG_NUM_SIZE-1] & 0x01) {
			y = cbig_num_mod(cbig_num_mul2(y, a), n);            
		}

		a =  cbig_num_mod(cbig_num_mul2(a, a), n);
		b = cbig_num_div(b, 2);
    }

    return y;
}

 
cbig_num_t crsa_encrypt(cbig_num_t plaintext, cbig_num_t e, cbig_num_t n) {
    return modexp(plaintext, e, n);
}

 
cbig_num_t crsa_decrypt(cbig_num_t ciphertext, cbig_num_t d, cbig_num_t n) {
    return modexp(ciphertext, d, n);
}
